package com.music.mysongs.fragment.option

import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.gson.Gson
import com.music.mysongs.R
import com.music.mysongs.adapter.CommonRecyclerAdapter
import com.music.mysongs.data.HistoryData
import com.music.mysongs.data.getTodayHistoryApi
import com.music.mysongs.file.FileOP
import com.music.mysongs.helper.*
import com.music.mysongs.utils.myLog
import com.music.mysongs.utils.myToastWithoutCxt
import com.music.mysongs.web.CommonWebTask
import kotlinx.android.synthetic.main.item_recycler_stag.view.*
import java.util.*

class HistoryFragment : Fragment() {
    private val mTAG = "HistoryFragment"
    private val codeHISTORY = 100

    private var historyData = ArrayList<HistoryData.HistoryList>()
    private var historyRecyclerView: RecyclerView? = null
    private val historyHandler: Handler = Handler {
        when (it.what) {
            codeHISTORY -> {
                myLog("$mTAG: historyData=$historyData")
                historyRecyclerView!!.adapter = CommonRecyclerAdapter.Builder()
                    .setData(historyData).setLayout(R.layout.item_recycler_stag)
                    .bindView { holder, innerData, position ->
                        val history = innerData as HistoryData.HistoryList
                        val title =
                            "${history.year}/${history.month}/${history.day}  ${history.title}"
                        holder.itemView.txtTitleStag_item.text = title
                        holder.itemView.txtContentStag_item.text =
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                                Html.fromHtml(history.content, Html.FROM_HTML_MODE_LEGACY)
                            } else {
                                history.content
                            }
                        holder.itemView.setOnClickListener {
                            myToastWithoutCxt(history.content, 1)
                        }
                    }.create()
            }
        }
        false
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initHistoryData()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        val v = inflater.inflate(R.layout.fragment_history, container, false)
        historyRecyclerView = v.findViewById(R.id.recyclerViewHistory_option)
        historyRecyclerView!!.layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        return v
    }

    private fun initHistoryData() {
        val date = Calendar.getInstance()
        val month = date.get(Calendar.MONTH) + 1
        val day = date.get(Calendar.DAY_OF_MONTH)
        //读文件
        val jsonFile = FileOP().read(this.requireActivity(), "history.json")
        //读时间
        val old = myActReadStringSPF(this.requireActivity(), "spfHistoryTime")
        myLog("$mTAG:old=$old")
        if (jsonFile.isEmpty() || old == "none" || getTimeMatch(
                getNow(),
                old.toString(), 1
            )
        ) {
            myLog("$mTAG: netHistory")
            getHistoryWebData(month, day)
        } else {
            myLog("$mTAG: fileHistory")
            val jData = Gson().fromJson(jsonFile, HistoryData.HistoryToday::class.java)
            historyData = jData.result
            val msg = Message()
            msg.what = codeHISTORY
            historyHandler.sendMessage(msg)
        }
    }

    //历史上的今天
    private fun getHistoryWebData(month: Int, day: Int) {
        val historyTask = CommonWebTask()
        historyTask.url = getTodayHistoryApi(month, day)
        historyTask.setCallbackHandler { innerData ->
            val data = Gson().fromJson(innerData, HistoryData.HistoryToday::class.java)
            myActWriteSPF(this.activity, "spfHistoryTime", getNow(), null)
            FileOP().save(this.requireActivity(), "history.json", innerData)
            historyData = data.result
            val msg = Message()
            msg.what = codeHISTORY
            historyHandler.sendMessage(msg)
        }
        historyTask.execute()
    }
}